package com.lin.zoo.dao;

import com.lin.zoo.dao.Interface.IDCookie;
import com.lin.zoo.po.*;
import com.lin.zoo.util.DataBase;

import java.sql.*;

public class CookieDao implements IDCookie {

    private Connection con;

    private PreparedStatement state;
    @Override
    public void setcookie(String name, String password){
        try {
            con = DataBase.getCon();//获取连接，通过DateBase处理好的通道，连接至mysql数据。
            String sql = "update cookie set name=?,password=? WHERE id=?";//设定mysql语句,更新cookie中的名字密码，没有添加新一行，永远只有一行，id=1
            state = con.prepareStatement(sql);
            state.setObject(1, name);
            state.setObject(2, password);
            state.setObject(3, 1);
            state.executeUpdate();
        }//捕捉异常
        catch (ClassNotFoundException | SQLException e) {
            System.out.println("数据库数据调用失败" + this.getClass().getName());
        } finally {
            try {
                DataBase.close(state, con);
            } catch (SQLException e) {
                System.out.println("连接关闭失败" + this.getClass().getName());
            }
        }

    }
    @Override
    public Cookie getcookie(){
        String name = null;
        String password = null;
        try {
            con = DataBase.getCon();
            //获取连接，通过DateBase处理好的通道，连接至mysql数据。
            String sql = "select name,password from cookie";
            //设定mysql语句
            state = con.prepareStatement(sql);
            ResultSet rs = state.executeQuery();
            while(rs.next()) {
                name = rs.getString("name");
                password = rs.getString("password");
            }
            System.out.println(name);
            System.out.println(password);
            return new Cookie(name,password);
        }//捕捉异常
        catch (ClassNotFoundException | SQLException e) {
            System.out.println("数据库数据调用失败" + this.getClass().getName());
        } finally {
            try {
                DataBase.close(state, con);
            } catch (SQLException e) {
                System.out.println("连接关闭失败" + this.getClass().getName());
            }
        }
        return new Cookie(name,password);
    }
}